package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageResult findAll(StudentQueryParam s) {
        PageHelper.startPage(s.getPage(), s.getPageSize());
        List<Student> rows = studentMapper.findAll(s);
        Page<Student> p = (Page<Student>) rows;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Transactional
    @Override
    public void deleteById(List<Integer> ids) {
        for(Integer id : ids){
            studentMapper.deleteById(id);
        }
    }

    @Override
    public void insert(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insert(student);
    }

    @Override
    public Student findById(Integer id) {
       return studentMapper.findById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Transactional
    @Override
    public void updateViolation(Integer id, String score) {
        if(score != null && !score.equals("0") && !score.isEmpty()){
            Integer scoreNew = Integer.parseInt(score);
            studentMapper.updateViolation(id, scoreNew);
        }
        Student st = new Student();
        st.setId(id);
        st.setUpdateTime(LocalDateTime.now());
        studentMapper.update(st);
    }
}
